<script setup>
import {onMounted, ref} from "vue"
import {ElMessage} from "element-plus";
import {Edit, Refresh, Search, Service} from "@element-plus/icons-vue";

onMounted(()=>{
  searchUsableInfo()
  checkIsClose()
})

const tableData = ref([])

//用来存储第一次查询到的电脑信息 供select选择框选择搜索
const computerData = ref([])
//声明一个异步的函数 获取所有电脑分类
import {getComputerList, getSearchComputer, openComputer, closeComputer, findUsableInfo} from "@/api/computer.js"
const ComputerList = async ()=> {
  let result = await getComputerList();
  tableData.value = result.date
  console.log(tableData.value)
}
ComputerList()

import { reactive } from 'vue'
import router from "@/router.js";

const formInline = reactive({
  price: '',
  detail: '',
})
// const userComputerCost = ref(0)

//模糊查询搜索电脑信息
const onSubmit = async () => {
  console.log('submit!')
  console.log(formInline)
  console.log(formInline.valueOf())
  let result = await getSearchComputer(formInline)
  console.log(result)
  tableData.value = result.date
}
const refreshSearchInfo = ()=>{
  formInline.price = ''
  formInline.detail = ''
}
const openComputerUserData = ref({
  username:"",
  computer:"",
  startTime:"",
  usableTime:"",
  usableBalance:""
})
//点击上机按钮 调用发送请求接口 传入电脑机型 并返回开始时间
import {useComputerStore} from "@/stores/useComputer.js";
const computerStore = useComputerStore()

// const clickComputerDetail = ref('')
const startUserComputer = async (row)=> {
  console.log(row)
  console.log("点击上机后获取到的电脑机型detail：" + row.detail)
  // clickComputerDetail.value = row.detail
  computerStore.setClickComputerDetail(row.detail)
  let result = await openComputer(row.detail)
  console.log(result)
  if (result.code == 200) {
    openComputerUserData.value.username = result.date.username
    openComputerUserData.value.computer = row.detail
    openComputerUserData.value.startTime = result.date.startTime
    openComputerUserData.value.usableTime = result.date.usableTime
    openComputerUserData.value.usableBalance = result.date.usableBalance
    ElMessage.success("上机成功，欢迎使用!")
    //设置上机信息存储中的值 存储在pinia
    computerStore.setInfo(openComputerUserData.value)
    computerStore.setDetail(row.detail)
    await router.push({name:'startUseComputer'})
    // await router.push('/board/startUseComputer/'+clickComputerDetail.value)
  }else {
    ElMessage.error(result.message?result.message : "用户已上机该电脑")
  }
  //定时查询可用时长和金额
  openTimer()
}
//测试上机函数修改
const startUserComputerInCard = async (ComputerData)=> {
  // clickComputerDetail.value = ComputerData.detail
  computerStore.setClickComputerDetail(ComputerData.detail)
  let result = await openComputer(ComputerData.detail)
  console.log(result)
  if (result.code == 200) {
    openComputerUserData.value.username = result.date.username
    openComputerUserData.value.computer = ComputerData.detail
    openComputerUserData.value.startTime = result.date.startTime
    openComputerUserData.value.usableTime = result.date.usableTime
    openComputerUserData.value.usableBalance = result.date.usableBalance
    ElMessage.success("上机成功，欢迎使用!")
    //设置上机信息存储中的值 存储在pinia
    computerStore.setInfo(openComputerUserData.value)
    computerStore.setDetail(ComputerData.detail)
    await router.push({name:'startUseComputer'})
    // await router.push('/board/startUseComputer/'+clickComputerDetail.value)
  }else {
    ElMessage.error(result.message?result.message : "用户已上机该电脑")
  }
  //定时查询可用时长和金额
  openTimer()
}
//
//设置定时器
let timerSearchUsableInfo
const openTimer = ()=> {
  clearInterval(timerSearchUsableInfo)
  timerSearchUsableInfo = setInterval(()=> {
    searchUsableInfo()
  },30000)
}
const closeTimer = ()=>{
  clearInterval(timerSearchUsableInfo)
}
//查询可用时长和金额
const searchUsableInfo = async (elMessage)=> {
  let result = await findUsableInfo(computerStore.clickComputerDetail.value)
  console.log(result)
  if (result.code == 200) {
    if (result.date.usableBalance == null) {
      openComputerUserData.value.usableTime = result.date.usableTime
    }else {
      openComputerUserData.value.usableTime = result.date.usableTime
      openComputerUserData.value.usableBalance = result.date.usableBalance
      computerStore.setInfoUsableBalance(result.date.usableBalance)
      //更新存储的值
      if (result.date.usableTime != null) {
        computerStore.setInfoUsableTime(openComputerUserData.value.usableTime)
      }


    }
    // computerStore.setInfo(openComputerUserData.value)
    if (elMessage == true) {
      ElMessage.success("查询成功")
    }
  }else{
    ElMessage.error(result.message?result.message : "查询失败，请确认是否已经上机")
  }
}


//点击下机按钮 调用接口
/*const endUserComputer = async (row)=> {
  let result = await closeComputer(row.detail)
  console.log(result)
  if (result.code == 200) {
    //userComputerCost.value = result.date
    computerStore.setUserComputerCost(result.date)
    closeTimer()
    //清空电脑信息的值，防止下机后再次查询仍然扣钱
    clickComputerDetail.value = ''
    //下机时再次查询可用余额 重新渲染
    searchUsableInfo()
    ElMessage.success("下机成功，消费 " + userComputerCost.value +" 元")
    await computerStore.removeInfo()
    await computerStore.removeDetail()
  }else {
    ElMessage.error("已下机，无需再次操作")
  }
}*/
//测试下机函数修改
const endUserComputerInCard = async (computerData)=> {
  let result = await closeComputer(computerData.detail)
  console.log(result)
  if (result.code == 200) {
    // userComputerCost.value = result.date
    computerStore.setUserComputerCost(result.date)
    closeTimer()
    //清空电脑信息的值，防止下机后再次查询仍然扣钱
    // clickComputerDetail.value = ''
    computerStore.removeClickComputerDetail()
    //下机时再次查询可用余额 重新渲染
    searchUsableInfo()
    ElMessage.success("下机成功，消费 " + computerStore.userComputerCost +" 元")
    await computerStore.removeInfo()
    await computerStore.removeDetail()
  }else {
    ElMessage.error("已下机，无需再次操作")
  }
}
const checkIsClose = ()=>{
  if (computerStore.isClose == true) {
    console.log("555555555555555556666666666")
    console.log(computerStore.isClose)
    closeTimer()
    //下机时再次查询可用余额 重新渲染
    searchUsableInfo()
    computerStore.removeIsClose()
  }
}
//

</script>

<template>
  <el-container>
    <el-header class="el-container-header">
      <div class="openComputerMessage">
        <ul>
          <li>
            <el-card style="max-width: 480px">
              <template #header>
                <div class="card-header">
                  <span>上机用户</span>
                </div>
              </template>
              <span class="text item diyItem">{{ computerStore.info == null ? '未开始上机' :computerStore.info.username}}</span>
            </el-card>
          </li>
          <li>
            <el-card style="max-width: 480px">
              <template #header>
                <div class="card-header">
                  <span>已上机</span>
                </div>
              </template>
              <span  class="text item diyItem">{{ computerStore.info == null ? '未开始上机' :computerStore.info.computer }}</span>
            </el-card>
          </li>
          <li>
            <el-card style="max-width: 480px">
              <template #header>
                <div class="card-header">
                  <span>开始时间</span>
                </div>
              </template>
              <span class="text item diyItem">{{ computerStore.info == null ? '未开始上机' :computerStore.info.startTime }}</span>
            </el-card>
          </li>
          <li>
            <el-card style="max-width: 480px">
              <template #header>
                <div class="card-header">
                  <span>剩余金额&时间</span>
                  <el-button class="searchButton" type="primary" round @click="searchUsableInfo(true)"><el-icon><Search/></el-icon>查询</el-button>
                </div>
              </template>
              <span class="text item">可用时长 {{ computerStore.info == null ? '' : computerStore.info.usableTime }}h |</span>
              <span class="text item"> 可用余额 {{ openComputerUserData.usableBalance }}元</span>
            </el-card>
          </li>
        </ul>
      </div>
      <!--            搜索框-->
      <div class="searchFormDiv">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="价格">
            <el-input v-model="formInline.price" placeholder="请输入电脑价格" @keyup="onSubmit"></el-input>
          </el-form-item>
          <el-form-item label="机型">
            <el-input v-model="formInline.detail" placeholder="请输入电脑类型" @keyup="onSubmit"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit"><el-icon><Search /></el-icon>搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="default" @click="ComputerList();refreshSearchInfo()"><el-icon><Refresh /></el-icon>重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-header>

    <el-main class="el-container-main">

<!--      <el-table :data="tableData" height="250" style="width: 100%" >
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="price" label="价格" width="180" />
        <el-table-column prop="detail" label="机型" />
        <el-table-column prop="" label="操作" >
          <template #default = "{ row }">
            <el-button type="primary" @click="() => startUserComputer(row)">上机</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" >
          <template #default = "{ row }">
            <el-button type="danger" plain @click="endUserComputer(row)">下机</el-button>
          </template>
        </el-table-column>
      </el-table>-->

      <div class="computerCard">
        <el-card style="max-width: 480px;" v-for="(ComputerData, index) in tableData">
          <template #header>电脑信息</template>
          <img
              src="https://lkpstudy.oss-cn-beijing.aliyuncs.com/%E7%94%B5%E8%84%91%E5%9B%BE%E7%89%87.png"
              style="width: 100px"
          />
          <ul>
            <li><span>价格：{{ ComputerData.price }}元</span></li>
            <li><span>机型：{{ ComputerData.detail }}</span></li>
            <li>
              <el-button type="primary" @click="() => startUserComputerInCard(ComputerData)">上机</el-button>
            </li>
            <li>
              <el-button type="danger" plain @click="endUserComputerInCard(ComputerData)">下机</el-button>
            </li>
          </ul>
        </el-card>
      </div>


    </el-main>
  </el-container>

</template>

<style scoped>

.el-container-header {
  /*background-color: #a5c5b7;*/
  height: 210px;
}
.aside-select li {
  list-style-type: none;
}

.card-header {
  height: 40px;
}
.diyItem {
  height: 30px;
}
.searchButton {
  float: right;
}
.openComputerMessage {

}
.openComputerMessage ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
  display: flex;
}
.openComputerMessage ul li {
  width: 400px;
}
.searchFormDiv {
  position: relative;
  top: 20px;
  /*bottom: 0px;*/
}
.el-container-main {
  /*background-color: #007bff;*/
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.computerCard {
  display: flex;
  flex-wrap: wrap;
  height: 750px;
}
.computerCard .el-card {
  margin: 20px;
  width: 300px;
  height: 330px;
}
.computerCard ul {
  padding: 0;
  margin: 0;
  list-style-type: none;
  display: flex;
  flex-wrap: wrap;
}
.computerCard ul li {
  margin: 10px;
}
</style>